<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提现申请</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f5f5f5;
            padding-top: 20px;
        }
        .withdrawal-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .card {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: none;
            margin-bottom: 20px;
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: bold;
        }
        .form-label {
            font-weight: 600;
            color: #333;
        }
        .required {
            color: red;
        }
        .account-type-card {
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
        }
        .account-type-card:hover {
            border-color: #667eea;
            background-color: #f8f9ff;
        }
        .account-type-card.active {
            border-color: #667eea;
            background-color: #e8ecff;
        }
        .account-type-card i {
            font-size: 24px;
            color: #667eea;
            margin-bottom: 10px;
        }
        .summary-box {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e9ecef;
        }
        .summary-item:last-child {
            border-bottom: none;
            font-size: 18px;
            font-weight: bold;
            color: #667eea;
        }
        .btn-submit {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            padding: 12px 40px;
            font-size: 16px;
            font-weight: 600;
        }
        .btn-submit:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            color: white;
        }
        .alert-custom {
            border-left: 4px solid #667eea;
            background-color: #f8f9ff;
        }
        .limit-info {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        .bank-select-section {
            display: none;
        }
        .bank-select-section.show {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container withdrawal-container">
        <div class="card">
            <div class="card-header text-center">
                <h4 class="mb-0"><i class="fas fa-money-bill-wave"></i> 提现申请</h4>
            </div>
            <div class="card-body">
                <!-- 提示信息 -->
                <div class="alert alert-custom">
                    <i class="fas fa-info-circle"></i>
                    <strong>温馨提示：</strong>
                    <ul class="mb-0">
                        <li>提现金额范围：100元 - 50,000元</li>
                        <li>每日最大提现金额：100,000元</li>
                        <li>提现手续费：0.5%（最低2元）</li>
                        <li>审核时间：1-3个工作日</li>
                    </ul>
                </div>

                <form id="withdrawalForm">
                    <!-- 提现金额 -->
                    <div class="mb-4">
                        <label class="form-label">
                            <span class="required">*</span> 提现金额
                        </label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-yen-sign"></i></span>
                            <input type="number" class="form-control" id="amount" placeholder="请输入提现金额" 
                                   min="100" max="50000" step="0.01" required>
                        </div>
                        <div class="limit-info">
                            <span id="amountHint">单笔最低100元，最高50,000元</span>
                        </div>
                        <div id="amountError" class="text-danger" style="display: none;"></div>
                    </div>

                    <!-- 收款账户类型 -->
                    <div class="mb-4">
                        <label class="form-label mb-3">
                            <span class="required">*</span> 收款账户类型
                        </label>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="account-type-card text-center" data-type="1">
                                    <i class="fas fa-credit-card"></i>
                                    <div>银行卡</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="account-type-card text-center" data-type="2">
                                    <i class="fab fa-alipay"></i>
                                    <div>支付宝</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="account-type-card text-center" data-type="3">
                                    <i class="fab fa-weixin"></i>
                                    <div>微信</div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="accountType" value="">
                    </div>

                    <!-- 银行卡信息 -->
                    <div id="bankSection" class="bank-select-section">
                        <div class="mb-3">
                            <label class="form-label">开户银行</label>
                            <input type="text" class="form-control" id="bankName" placeholder="请输入开户银行名称">
                        </div>
                    </div>

                    <!-- 收款账号 -->
                    <div class="mb-4">
                        <label class="form-label">
                            <span class="required">*</span> 收款账号
                        </label>
                        <input type="text" class="form-control" id="accountNumber" 
                               placeholder="请输入收款账号" required>
                        <div class="limit-info" id="accountHint">请确保账号正确，提现成功后无法撤销</div>
                        <div id="accountError" class="text-danger" style="display: none;"></div>
                    </div>

                    <!-- 收款人姓名 -->
                    <div class="mb-4">
                        <label class="form-label">
                            <span class="required">*</span> 收款人姓名
                        </label>
                        <input type="text" class="form-control" id="accountName" 
                               placeholder="请输入收款人真实姓名" required>
                        <div class="limit-info">必须与银行账户或支付宝、微信实名信息一致</div>
                        <div id="accountNameError" class="text-danger" style="display: none;"></div>
                    </div>

                    <!-- 支付密码 -->
                    <div class="mb-4">
                        <label class="form-label">
                            <span class="required">*</span> 支付密码
                        </label>
                        <input type="password" class="form-control" id="password" 
                               placeholder="请输入6位支付密码" maxlength="6" required>
                        <div class="limit-info">用于确认提现操作</div>
                    </div>

                    <!-- 短信验证码 -->
                    <div class="mb-4">
                        <label class="form-label">短信验证码</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="verifyCode" 
                                   placeholder="请输入6位验证码" maxlength="6">
                            <button class="btn btn-outline-secondary" type="button" id="sendCodeBtn">
                                获取验证码
                            </button>
                        </div>
                        <div class="limit-info">大额提现时需要验证</div>
                    </div>

                    <!-- 提现汇总 -->
                    <div class="summary-box">
                        <h6 class="mb-3"><i class="fas fa-clipboard-list"></i> 提现汇总</h6>
                        <div class="summary-item">
                            <span>提现金额：</span>
                            <span id="summaryAmount">¥ 0.00</span>
                        </div>
                        <div class="summary-item">
                            <span>手续费：</span>
                            <span id="summaryFee">¥ 0.00</span>
                        </div>
                        <div class="summary-item">
                            <span>实际到账：</span>
                            <span id="summaryActual">¥ 0.00</span>
                        </div>
                    </div>

                    <!-- 提交按钮 -->
                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-submit">
                            <i class="fas fa-paper-plane"></i> 提交申请
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 提现记录 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-history"></i> 提现记录</h5>
            </div>
            <div class="card-body">
                <div id="recordSection">
                    <!-- 提现记录将在这里动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 成功模态框 -->
    <div class="modal fade" id="successModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body text-center py-4">
                    <i class="fas fa-check-circle text-success" style="font-size: 48px;"></i>
                    <h5 class="mt-3">提现申请已提交</h5>
                    <p class="text-muted">我们将在1-3个工作日内完成审核</p>
                    <div class="mt-3">
                        <button class="btn btn-primary" data-bs-dismiss="modal">确定</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ====== 统计面板区块 START  ====== -->
<div class="card mb-4">
  <div class="card-header">
    <h5><i class="fas fa-chart-bar"></i> 提现数据统计</h5>
  </div>
  <div class="card-body">
    <form class="row g-3" id="amountPanelForm">
      <div class="col-md-3">
        <label class="form-label">开始日期</label>
        <input type="date" class="form-control" id="statStart">
      </div>
      <div class="col-md-3">
        <label class="form-label">结束日期</label>
        <input type="date" class="form-control" id="statEnd">
      </div>
      <div class="col-md-3">
        <label class="form-label">分组方式</label>
        <select class="form-select" id="statGroup">
          <option value="1">按日</option>
          <option value="2">按月</option>
          <option value="3">按年</option>
        </select>
      </div>
      <div class="col-md-3 align-self-end">
        <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> 查询</button>
      </div>
    </form>
    <!-- 柱状图容器  -->
    <div id="amountChart" style="width:100%;height:400px;"></div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script>
<script>
(function(){
  const chart = echarts.init(document.getElementById('amountChart'));
  function renderChart(x, y) {
    chart.setOption({
      tooltip: {trigger: 'axis'},
      xAxis: {type: 'category', data: x, axisLabel:{rotate:35}},
      yAxis: {type: 'value', name: '金额(元)'},
      series: [{
        data: y,
        type: 'bar',
        barWidth:20,
        color: '#667eea',
        label:{show: true, position: 'top'}
      }]
    });
  }
  function loadPanelData(e) {
    if(e) e.preventDefault();
    const start = document.getElementById('statStart').value;
    const end = document.getElementById('statEnd').value;
    const group = document.getElementById('statGroup').value;
    const token = localStorage.getItem('token') || '';
    
    fetch(`/v1/withdrawal/amount_panel?start_time=${start}&end_time=${end}&group_type=${group}`, {
      headers: { 
        'Authorization': `Bearer ${token}`,
        'x-token': token
      }
    })
    .then(async res => {
      const contentType = res.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        const text = await res.text();
        console.error('Expected JSON but got:', text.substring(0, 100));
        throw new Error(`服务器返回非JSON格式，状态码: ${res.status}`);
      }
      return res.json();
    })
    .then(d => {
      if(d.code === 200 && d.data){renderChart(d.data.x_axis, d.data.y_axis);}
      else{ alert(d.msg || '统计数据获取失败');}
    })
    .catch(err => {
      console.error('加载统计数据失败:', err);
      alert('统计数据获取失败: ' + err.message);
    });
  }
  document.getElementById('amountPanelForm').addEventListener('submit', loadPanelData);
  loadPanelData();
})();
</script>
<!-- ====== 统计面板区块 END  ====== -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const API_BASE_URL = '/v1/withdrawal';
        
        // 选择账户类型
        document.querySelectorAll('.account-type-card').forEach(card => {
            card.addEventListener('click', function() {
                document.querySelectorAll('.account-type-card').forEach(c => c.classList.remove('active'));
                this.classList.add('active');
                const accountType = this.dataset.type;
                document.getElementById('accountType').value = accountType;
                
                // 显示/隐藏银行卡输入框
                const bankSection = document.getElementById('bankSection');
                if (accountType === '1') {
                    bankSection.classList.add('show');
                    document.getElementById('accountHint').textContent = '请输入银行卡号';
                } else if (accountType === '2') {
                    bankSection.classList.remove('show');
                    document.getElementById('accountHint').textContent = '请输入支付宝账号';
                } else if (accountType === '3') {
                    bankSection.classList.remove('show');
                    document.getElementById('accountHint').textContent = '请输入微信账号';
                }
            });
        });

        // 计算手续费和实际到账
        function calculateFee() {
            const amount = parseFloat(document.getElementById('amount').value) || 0;
            const feeRate = 0.005; // 0.5%
            const minFee = 2;
            
            let fee = amount * feeRate;
            if (fee < minFee) {
                fee = minFee;
            }
            
            const actual = amount - fee;
            
            document.getElementById('summaryAmount').textContent = `¥ ${amount.toFixed(2)}`;
            document.getElementById('summaryFee').textContent = `¥ ${fee.toFixed(2)}`;
            document.getElementById('summaryActual').textContent = `¥ ${actual.toFixed(2)}`;
        }

        document.getElementById('amount').addEventListener('input', calculateFee);

        // 提交表单
        document.getElementById('withdrawalForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const amount = parseFloat(document.getElementById('amount').value);
            const accountType = document.getElementById('accountType').value;
            const accountNumber = document.getElementById('accountNumber').value;
            const accountName = document.getElementById('accountName').value;
            const bankName = document.getElementById('bankName').value;
            const password = document.getElementById('password').value;
            const verifyCode = document.getElementById('verifyCode').value;

            // 验证
            if (!amount || amount < 100 || amount > 50000) {
                alert('提现金额必须在100-50000元之间');
                return;
            }

            if (!accountType) {
                alert('请选择收款账户类型');
                return;
            }

            if (!accountNumber || !accountName) {
                alert('请填写完整的收款账户信息');
                return;
            }

            if (!password || password.length !== 6) {
                alert('请输入6位支付密码');
                return;
            }

            // 获取token
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                window.location.href = '/login';
                return;
            }

            try {
                const response = await fetch(`${API_BASE_URL}/create`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`,
                        'x-token': token
                    },
                    body: JSON.stringify({
                        amount: amount,
                        account_type: parseInt(accountType),
                        account_number: accountNumber,
                        account_name: accountName,
                        bank_name: bankName,
                        password: password,
                        verify_code: verifyCode
                    })
                });

                // 检查响应格式
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    const text = await response.text();
                    console.error('Expected JSON but got:', text.substring(0, 200));
                    throw new Error(`服务器返回非JSON格式，状态码: ${response.status}`);
                }

                const data = await response.json();
                
                if (response.ok && data.code === 200) {
                    // 显示成功提示
                    const modal = new bootstrap.Modal(document.getElementById('successModal'));
                    modal.show();
                    
                    // 重置表单
                    this.reset();
                    document.querySelectorAll('.account-type-card').forEach(c => c.classList.remove('active'));
                    document.getElementById('summaryAmount').textContent = '¥ 0.00';
                    document.getElementById('summaryFee').textContent = '¥ 0.00';
                    document.getElementById('summaryActual').textContent = '¥ 0.00';
                    
                    // 刷新提现记录
                    loadWithdrawalRecords();
                } else {
                    alert(data.msg || '提现申请失败');
                }
            } catch (error) {
                console.error('Error:', error);
                if (error instanceof TypeError && error.message.includes('JSON')) {
                    alert('服务器响应格式错误，请检查网络连接或联系管理员');
                } else {
                    alert('提交失败: ' + error.message);
                }
            }
        });

        // 加载提现记录
        async function loadWithdrawalRecords() {
            const token = localStorage.getItem('token');
            if (!token) {
                console.warn('未找到token，跳过加载提现记录');
                return;
            }

            try {
                const response = await fetch(`${API_BASE_URL}/list?page=1&page_size=10`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'x-token': token
                    }
                });
                
                // 检查响应格式
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    const text = await response.text();
                    console.error('Expected JSON but got:', text.substring(0, 200));
                    throw new Error(`服务器返回非JSON格式，状态码: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (response.ok && data.code === 200 && data.data) {
                    const records = data.data.list || [];
                    const recordSection = document.getElementById('recordSection');
                    
                    if (records.length === 0) {
                        recordSection.innerHTML = '<p class="text-center text-muted">暂无提现记录</p>';
                        return;
                    }
                    
                    let html = '<div class="table-responsive"><table class="table table-hover"><thead><tr>';
                    html += '<th>提现单号</th><th>金额</th><th>收款账户</th><th>状态</th><th>申请时间</th></tr></thead><tbody>';
                    
                    records.forEach(record => {
                        const statusText = getStatusText(record.status);
                        const statusClass = getStatusClass(record.status);
                        html += `<tr>
                            <td>${record.withdrawal_no || ''}</td>
                            <td>¥ ${record.amount || 0}</td>
                            <td>${record.account_name || ''}</td>
                            <td><span class="badge ${statusClass}">${statusText}</span></td>
                            <td>${new Date(record.created_at).toLocaleString()}</td>
                        </tr>`;
                    });
                    
                    html += '</tbody></table></div>';
                    recordSection.innerHTML = html;
                }
            } catch (error) {
                console.error('Error loading records:', error);
            }
        }

        function getStatusText(status) {
            const statusMap = {
                0: '待审核',
                1: '审核通过',
                2: '审核拒绝',
                3: '提现中',
                4: '提现成功',
                5: '提现失败'
            };
            return statusMap[status] || '未知';
        }

        function getStatusClass(status) {
            const classMap = {
                0: 'bg-warning',
                1: 'bg-success',
                2: 'bg-danger',
                3: 'bg-info',
                4: 'bg-success',
                5: 'bg-danger'
            };
            return classMap[status] || 'bg-secondary';
        }

        // 页面加载时加载提现记录
        window.addEventListener('load', loadWithdrawalRecords);

        // 发送验证码（示例，需要对接实际API）
        let codeSeconds = 60;
        let codeTimer = null;
        const sendBtn = document.getElementById('sendCodeBtn');
        function startCodeTimer() {
          sendBtn.disabled = true;
          let sec = codeSeconds;
          sendBtn.textContent = `${sec}秒后重试`;
          codeTimer = setInterval(() => {
            sec--;
            sendBtn.textContent = sec > 0 ? `${sec}秒后重试` : '获取验证码';
            if (sec <= 0) {
              clearInterval(codeTimer);
              sendBtn.disabled = false;
            }
          }, 1000);
        }
        sendBtn.addEventListener('click', function() {
          const token = localStorage.getItem('token');
          if (!token) return alert('请先登录！');
          // 如需手机号，补充获取方式
          fetch('/v1/user/send_sms', {
            method: 'POST',
            headers: { 
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`,
              'x-token': token
            },
            body: JSON.stringify({})
          })
          .then(async res => {
            const contentType = res.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
              const text = await res.text();
              console.error('Expected JSON but got:', text.substring(0, 200));
              throw new Error(`服务器返回非JSON格式，状态码: ${res.status}`);
            }
            return res.json();
          })
          .then(data => {
            if(data.code === 200){
              alert('验证码发送成功！');
              startCodeTimer();
            }else{
              alert(data.msg || '短信发送失败');
            }
          })
          .catch(err => {
            console.error('发送验证码失败:', err);
            alert('发送验证码失败: ' + err.message);
          });
        });
    </script>
</body>
</html>

